package com.zhuotiao.crm.web.demo;

import com.github.pagehelper.Page;
import com.pikachu.common.annotion.Permission;
import com.pikachu.common.exception.BizException;
import com.pikachu.web.Result;
import com.pikachu.web.pojo.PageBean;
import com.pikachu.web.util.HttpParamUtils;
import com.pikachu.web.util.JsonUtils;
import com.zhuotiao.crm.model.dto.DemoEntity;
import com.zhuotiao.crm.service.demo.IDemoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by dongyang.yu on 18-8-27.
 */
@RestController
@RequestMapping("/test")
@Api(value = "测试", tags = {"测试"})
@CrossOrigin(origins = "*", maxAge = 3600)
@Validated
@Slf4j
@AllArgsConstructor
public class DemoController {

    private final IDemoService demoService;
    //private final StringRedisTemplate redisTemplate;

    /**
     *  增
     * @param demoEntity
     * @param response
     * @param request
     * @param result
     * @return
     */
    @ApiOperation(value="添加",httpMethod="POST")
    @PostMapping("/add")
    public Result<Void> add(@Valid @RequestBody DemoEntity demoEntity,
                      HttpServletResponse response,
                      HttpServletRequest request, BindingResult result) {
        this.demoService.addDemo(demoEntity);
        return Result.success();
    }

    /**
     * 删
     * @param id
     * @return
     */
    @ApiOperation(value="删除",httpMethod="POST")
    @PostMapping("/del")
    public Result<Void> del(Long id) {
        this.demoService.delDemo(id);
        return Result.success();
    }

    /**
     *  修改
     * @param demoEntity+++++
     * @param response
     * @param request
     * @param result
     * @return
     */
    @ApiOperation(value="修改",httpMethod="POST")
    @PostMapping("/update")
    public Result<Void> update(@Valid @RequestBody DemoEntity demoEntity,
                                         HttpServletResponse response,
                                         HttpServletRequest request, BindingResult result) {
        this.demoService.updateDemo(demoEntity);
        return Result.success();
    }

    /**
     * 查询
     * 使用tk
     * @param id
     * @return
     */
    @ApiOperation(value = "查询，使用tk")
    @GetMapping("/detail")
    @Permission("test")
    public Result<DemoEntity> testJson(HttpServletRequest request, Long id){
        //写缓存
        try {
            int a = new Random().nextInt(1000);
//            this.redisTemplate.opsForValue().set(a + "", a + "");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> test");
        DemoEntity demoEntity = this.demoService.selelctOne(id);
        return Result.success(demoEntity);
    }

    /**
     * 查询
     * 执行XML的sql
     * @param id
     * @return
     */
    @ApiOperation(value = "查询List，使用XML")
    @GetMapping("/xml")
    public Result<List<DemoEntity>> getXMl(Long id){
        List<DemoEntity> demoEntity = this.demoService.getListXML();
        return Result.success(demoEntity);
    }

    /**
     * 分页
     *
     * 虽然所有的参数都可以从request里取出来，但是在写controller的时候，必须把所有的参数都写一次，
     * 这样后期容易找该接口需要的参数
     *
     * 不是必填的参数可以设置 required = false
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value="分页，使用tk",httpMethod="GET")
    @ResponseBody
    public Result<Page<List<DemoEntity>>> getpage(HttpServletResponse response, HttpServletRequest request,
                         @RequestParam(value = "page_no", required = false) String pageNo,
                         @RequestParam(value = "page_size", required = false) String pageSize,
                         @ApiParam(value = "demo")
                         @RequestParam(required = false) String param) {
        Map<String, Object> paramMap = HttpParamUtils.getParamsByGet(request);
        PageBean pageBean = JsonUtils.mapToObject(paramMap, PageBean.class);
        Page<List<DemoEntity>> listPage = this.demoService.selectPage(pageBean, param);
        return Result.successPage(listPage);
    }

    @ApiOperation(value="自定义异常",httpMethod="GET")
    @GetMapping("/servererror")
    public Result<Void> serverError() {
        throw new BizException("001001", "发生义务异常");
    }

    @ApiOperation(value="参数异常，统一返回",httpMethod="POST")
    @PostMapping("/paramerror")
    public Result<Void> paramError(@Validated @RequestBody ValidationDemo validationDemo) {
        return Result.success();
    }

    public static class ValidationDemo {
        @NotBlank(message = "用户名不能为空")
        private String userName;
    }

}
